package com.my.financial.repository;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.my.financial.domain.User;

@Repository
public class UserRepository {
	@Autowired
	private SessionFactory sessionFactory;
	
	public Session getSession() {
		return this.sessionFactory.getCurrentSession();
	}
	
	public Long save(User user){
		Long id = (Long) getSession().save(user);
		return id;
	}
	
	public void addMember(String member,Long userId) {
		String hql = "update "+User.class.getName()+ " f set f.allMembers=concat(f.allMembers,:member) where id = :id";
		Query query = this.getSession().createQuery(hql)
				.setParameter("member", ","+member).setParameter("id", userId);
		query.executeUpdate();
	}
	
	public void deleteMember(String member,Long userId) {
		String hql = "update "+User.class.getName()+ " f set f.allMembers=replace(f.allMembers,:member,'') where id = :id";
		Query query = this.getSession().createQuery(hql)
				.setParameter("member", ","+member).setParameter("id", userId);
		query.executeUpdate();
	}
	
	public void delete(User user){
		getSession().delete(user);
	}
	
	public void update(User user){
		getSession().update(user);
	}
	
	public User findByUserNameAndPassword(String userName,String password){
		String hql = "from " + User.class.getName()+" u where u.userName=:userName and u.password=:password";
		Query query = getSession().createQuery(hql);
		query.setParameter("userName", userName);
		query.setParameter("password", password);
		return (User) query.uniqueResult();
	}
	
	public User findById(Long userId) {
		return (User) this.getSession().get(User.class, userId);
	}
	
	/**
	 * AJax验证用户名是否已存在
	 * @param userName
	 * @return
	 */
	public User findByUserName(String userName) {
		String hql = "from " + User.class.getName()+" u where u.userName=:userName";
		Query query = getSession().createQuery(hql);
		query.setParameter("userName", userName);
		return (User) query.uniqueResult();
	}
	
	public String findAllMembersById(Long userId) {
		String hql = "select u.allMembers from " + User.class.getName() + " u where id = :id";
		Query query = this.getSession().createQuery(hql);
		query.setParameter("id", userId);
		return (String) query.uniqueResult();
	}
}
